package com.java.TCP.upload_file_thread_pool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {
    static class RunnableSon implements Runnable {
        private Socket socket;

        public RunnableSon(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                String fileName = UUID.randomUUID().toString();
                String path = "网络编程\\com\\java\\TCP\\upload_file_thread_pool\\files\\" + fileName + ".jpg";
                BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(path));

                // 将接收到的文件写到本地
                int length;
                byte[] buffer = new byte[1024];
                while ((length = bufferedInputStream.read(buffer)) != -1) {
                    bufferedOutputStream.write(buffer, 0, length);
                }

                // 发送上传成功或失败的反馈给客户端
                socket.getOutputStream().write("上传成功".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);

        // 最大线程数通过公式计算，此处为IO密集型
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 16, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2));

        while (true) {
            Socket socket = serverSocket.accept();
            threadPoolExecutor.execute(new RunnableSon(socket));
        }
    }
}
